﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.DTO.ProductionSystem;
using ThridGroup.ERP.RBAC;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 生产派单服务，实现生产派单相关的业务逻辑
    /// </summary>
    public class OrderDispatchServices : ApplicationService, IOrderDispatchServices
    {
        private readonly IRepository<OrderDispatch, int> _orderDispatchrepository;
        private readonly IRepository<User, int> _userrepository;

        /// <summary>
        /// 构造函数，注入生产派单仓储和用户仓储
        /// </summary>
        /// <param name="orderDispatchrepository">生产派单仓储</param>
        /// <param name="userrepository">用户仓储</param>
        public OrderDispatchServices(IRepository<OrderDispatch, int> orderDispatchrepository, IRepository<User, int> userrepository)
        {
            _orderDispatchrepository = orderDispatchrepository;
            _userrepository = userrepository;
        }

        /// <summary>
        /// 添加生产派单
        /// </summary>
        /// <param name="createOrderDispatchDto">生产派单创建DTO</param>
        /// <returns>返回新建派单的主键ID</returns>
        public async Task<int> AddOrderDispatch(CreateOrderDispatchDto createOrderDispatchDto)
        {
            var entity = ObjectMapper.Map<CreateOrderDispatchDto, OrderDispatch>(createOrderDispatchDto);
            await _orderDispatchrepository.InsertAsync(entity);
            return entity.Id;
        }

        /// <summary>
        /// 批量删除生产派单
        /// </summary>
        /// <param name="ids">要删除的ID列表</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> BatchDeleteAsync(List<int> ids)
        {
            foreach (var id in ids)
            {
                await _orderDispatchrepository.DeleteAsync(id);
            }
            return ids.Count;
        }

        /// <summary>
        /// 批量更新生产派单
        /// </summary>
        /// <param name="dtos">要更新的生产派单DTO列表</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> BatchUpdateAsync(List<CreateOrderDispatchDto> dtos)
        {
            foreach (var dto in dtos)
            {
                var entity = await _orderDispatchrepository.GetAsync(dto.Id);
                ObjectMapper.Map(dto, entity);
                await _orderDispatchrepository.UpdateAsync(entity);
            }
            return dtos.Count;
        }

        /// <summary>
        /// 删除单个生产派单
        /// </summary>
        /// <param name="id">要删除的ID</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> DeleteAsync(int id)
        {
            await _orderDispatchrepository.DeleteAsync(id);
            return 1;
        }

        /// <summary>
        /// 根据ID获取生产派单详情（用于反填）
        /// </summary>
        /// <param name="id">生产派单ID</param>
        /// <returns>生产派单详情</returns>
        public async Task<OrderDispatchDtoListDto> GetByIdAsync(int id)
        {
            var entity = await _orderDispatchrepository.GetAsync(id);
            var user = entity.UserId > 0 ? await _userrepository.GetAsync(entity.UserId) : null;
            var dto = ObjectMapper.Map<OrderDispatch, OrderDispatchDtoListDto>(entity);
            if (user != null)
            {
                dto.UserName = user.UserName;
                dto.UserPwd = user.UserPwd;
                dto.UserNickName = user.UserNickName;
            }
            return dto;
        }

        /// <summary>
        /// 根据ID列表批量获取生产派单详情（用于批量反填）
        /// </summary>
        /// <param name="ids">ID列表</param>
        /// <returns>生产派单详情列表</returns>
        public async Task<List<OrderDispatchDtoListDto>> GetByIdsAsync(List<int> ids)
        {
            var entities = await _orderDispatchrepository.GetListAsync(x => ids.Contains(x.Id));
            var userIds = entities.Select(x => x.UserId).Distinct().ToList();
            var users = await _userrepository.GetListAsync(x => userIds.Contains(x.Id));
            var dtos = new List<OrderDispatchDtoListDto>();
            foreach (var entity in entities)
            {
                var dto = ObjectMapper.Map<OrderDispatch, OrderDispatchDtoListDto>(entity);
                var user = users.FirstOrDefault(u => u.Id == entity.UserId);
                if (user != null)
                {
                    dto.UserName = user.UserName;
                    dto.UserPwd = user.UserPwd;
                    dto.UserNickName = user.UserNickName;
                }
                dtos.Add(dto);
            }
            return dtos;
        }

        /// <summary>
        /// 分页获取生产派单列表，并联查用户信息
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="limit">每页数量</param>
        /// <param name="taskName">任务名称（可选）</param>
        /// <param name="productionOrderCode">生产工单编号（可选）</param>
        /// <param name="processesName">工序名称（可选）</param>
        /// <returns>返回分页后的生产派单及用户信息列表</returns>
        public async Task<PagedResultDto<OrderDispatchDtoListDto>> GetOrderDispatchList(int page, int limit, string taskName = null, string productionOrderCode = null, string processesName = null)
        {
            // 获取所有生产派单数据
            var orderDispatchList = await _orderDispatchrepository.GetListAsync();
            // 条件过滤
            if (!string.IsNullOrEmpty(taskName))
                orderDispatchList = orderDispatchList.Where(x => x.TaskName.Contains(taskName)).ToList();
            if (!string.IsNullOrEmpty(productionOrderCode))
                orderDispatchList = orderDispatchList.Where(x => x.ProductionOrderCode.Contains(productionOrderCode)).ToList();
            if (!string.IsNullOrEmpty(processesName))
                orderDispatchList = orderDispatchList.Where(x => x.ProcessesName.Contains(processesName)).ToList();

            // 获取所有用户数据
            var userList = await _userrepository.GetListAsync();

            // 联查并组装DTO
            var query = from od in orderDispatchList
                        join u in userList on od.UserId equals u.Id into od_u
                        from u in od_u.DefaultIfEmpty()
                        select new OrderDispatchDtoListDto
                        {
                            Id = od.Id,
                            ProductionOrderCode = od.ProductionOrderCode,
                            TaskName = od.TaskName,
                            WorkstationName = od.WorkstationName,
                            ProcessesName = od.ProcessesName,
                            ProductionName = od.ProductionName,
                            StartTime = od.StartTime,
                            EndTime = od.EndTime,
                            DispatchName = od.DispatchName,
                            CreateTime = od.CreateTime,
                            UpdateTime = od.UpdateTime,
                            UserId = od.UserId,
                            UserName =u.UserName,
                            UserPwd = u.UserPwd,
                            UserNickName=u.UserNickName,
                        };

            // 排序：新数据在前
            query = query.OrderByDescending(x => x.Id);

            // 分页
            var totalCount = query.Count();
            var items = query.Skip((page - 1) * limit).Take(limit).ToList();

            return new PagedResultDto<OrderDispatchDtoListDto>(totalCount, items);
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="showUserDTO">用户查询参数DTO</param>
        /// <returns>返回用户DTO列表</returns>
        public async Task<List<UserDTO>> ShowUser(ShowUserDTO showUserDTO)
        {
            var userList = await _userrepository.GetListAsync();
            userList = userList.WhereIf(!string.IsNullOrEmpty(showUserDTO.UserName), m => m.UserName.Contains(showUserDTO.UserName)).ToList();
            userList = userList.WhereIf(!string.IsNullOrEmpty(showUserDTO.UserNickName), m => m.UserNickName.Contains(showUserDTO.UserNickName)).ToList();
            var result = ObjectMapper.Map<List<User>, List<UserDTO>>(userList);
            return result;
        }

        /// <summary>
        /// 更新单个生产派单
        /// </summary>
        /// <param name="dto">要更新的生产派单DTO</param>
        /// <returns>受影响的行数</returns>
        public async Task<int> UpdateAsync(CreateOrderDispatchDto dto)
        {
            var entity = await _orderDispatchrepository.GetAsync(dto.Id);
            ObjectMapper.Map(dto, entity);
            await _orderDispatchrepository.UpdateAsync(entity);
            return 1;
        }
    }
}

